package demo;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

import java.nio.charset.StandardCharsets;

/**
 * 同消息消费者
 */
public class SyncConsumerMessage {
    public static void main(String[] args) throws Exception {
        // Instantiate with specified consumer group name.
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("syncConsumerGroup");

        // Specify name server addresses.
        consumer.setNamesrvAddr("192.168.86.104:10001");

        // Subscribe one more more topics to consume.
        consumer.subscribe("demo_topic", "*");

        // Register callback to execute on arrival of messages fetched from brokers.
        consumer.registerMessageListener((MessageListenerConcurrently) (msgs, context) -> {
            String threadName = Thread.currentThread().getName();
            for(MessageExt msg:msgs) {
                System.out.printf("%-43s Receive New Messages: %s %s %n",threadName,msg.getTags(),
                        new String(msg.getBody(), StandardCharsets.UTF_8));
            }
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        });

        //Launch the consumer instance.
        consumer.start();

        System.out.printf("Consumer Started.%n");
    }
}
